<template>
  <!--表格翻页-->
  <div class="page-ctrl">
    <div class="page-num f-l">
      每页{{pageSize}}条数据，总共{{allDataSum}}条数据；当前页数{{current+'/'+allpage}}
    </div>
    <div class="page-main f-r">
      <button class="btn btn-info f-l"  @click="goto(current, 'pre')">上一页</button>
      <ul class="page-num f-l">
        <li v-for="index in pages" @click="goto(index, 'page')" :class="{'active':current === index}" :key="index">{{index}}</li>
      </ul>
      <button  class="btn btn-info f-l"  @click="goto(current, 'next')">下一页</button>
    </div>
  </div>
</template>

<script>
export default {
  name: 'pages',
  props: {
    showItem: Number, //页数条目
    allpage: Number, //全部页面
    pageSize: Number, //条目数
    allDataSum: Number //总条数
  },
  data() {
    return {
      current: 1,
    }
  },
  methods: {
    goto: function (index,str) {
      if (str === 'page') {
        if (index === this.current) return;
      }
      else if (str === 'pre') {  //上一页
        index --;
        if(index < 1){
          index = 1;
        }
      }
      else if (str === 'next') {  //下一页
        index ++;
        if(index > this.allpage){
          index = this.allpage;
        }
      }
      this.current = index;
    }
  },
  computed:{
    pages() {
      var pag = [];
      if (this.current < this.showItem) { //如果当前的激活的项 小于要显示的条数
        //总页数和要显示的条数那个大就显示多少条
        var i = Math.min(this.showItem, this.allpage);
        while (i) {
          pag.unshift(i--);
        }
      } else { //当前页数大于显示页数了
        var middle = this.current - Math.floor(this.showItem / 2),//从哪里开始
          i = this.showItem;
        if (middle > (this.allpage - this.showItem)) {
          middle = (this.allpage - this.showItem) + 1
        }
        while (i--) {
          pag.push(middle++);
        }
      }
      return pag
    }
  },
  watch: {
    current() { //当前页数改变通知父组件重新请求数据
      this.$emit('current-change', this.current)
    },
    allDataSum(newval,lodval){
      this.current = 1;
    }
  }
}
</script>

